// src/features/theme/themeSlice.ts
import { createSlice } from '@reduxjs/toolkit';

type ThemeState = {
  currentTheme: 'beijing' | 'beijings'; // 对应你现有的两个主题类名
};

// 从本地存储获取初始主题
const getInitialTheme = (): ThemeState['currentTheme'] => {
  if (typeof window !== 'undefined') {
    const savedTheme = localStorage.getItem('theme') as ThemeState['currentTheme'] | null;
    if (savedTheme) return savedTheme;
  }
  return 'beijing'; // 默认主题
};

const initialState: ThemeState = {
  currentTheme: getInitialTheme()
};

const themeSlice = createSlice({
  name: 'theme',
  initialState,
  reducers: {
    toggleTheme: (state) => {
      state.currentTheme = state.currentTheme === 'beijing' ? 'beijings' : 'beijing';
      localStorage.setItem('theme', state.currentTheme);
    },
    setTheme: (state, action: { payload: ThemeState['currentTheme'] }) => {
      state.currentTheme = action.payload;
      localStorage.setItem('theme', action.payload);
    }
  }
});

export const { toggleTheme, setTheme } = themeSlice.actions;
export const selectCurrentTheme = (state: { theme: ThemeState }) => state.theme.currentTheme;
export default themeSlice.reducer;